const extend = function extend(target) {
	var sources = Array.prototype.slice.call(arguments, 1)

	for (var i = 0; i < sources.length; i += 1) {
		var source = sources[i]
		for (var key in source) {
			if (source.hasOwnProperty(key)) {
				target[key] = source[key]
			}
		}
	}

	return target
}

/**
 * 获取当前时间戳
 */
const getTimestamp = (date) => {
	date = date || new Date()
	return Math.round(date / 1000)
}

/**
 * 保留指定小数位
 */
const toDecimal = (float, num) => {
	if (typeof float !== 'number') float = parseFloat(float)
	return parseFloat(float.toFixed(num))
}

/**
 * 时间戳转 yyyy-MM-dd hh:mm
 */
export function formatDate(timestamp, format) {
	const date = timestamp ? new Date(timestamp * 1000) : new Date();
	const data = {
		'M+': date.getMonth() + 1,
		'd+': date.getDate(),
		'h+': date.getHours(),
		'm+': date.getMinutes(),
		's+': date.getSeconds(),
		'q+': Math.floor((date.getMonth() + 3) / 3),
		'S+': date.getMilliseconds()
	}
	if (/(y+)/i.test(format)) {
		format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
	}
	for (var key in data) {
		if (new RegExp('(' + key + ')').test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ?
				data[key] : ('00' + data[key]).substr(('' + data[key]).length))
		}
	}

	return format
}

/**
 * 分钟、小时、天前的处理
 */
const timeAgo = function(timestamp, format) {
	const minute = 1000 * 60 // 把分，时，天，周，半个月，一个月用毫秒表示
	const hour = minute * 60
	const day = hour * 24
	const now = new Date().getTime() // 获取当前时间毫秒
	const spreadTime = now - timestamp * 1000 // 时间差
	if (spreadTime < 0) {
		return
	}


	const minC = spreadTime / minute
	const hourC = spreadTime / hour
	const dayC = spreadTime / day
	let result

	if (spreadTime >= 0 && spreadTime <= minute) {
		result = '刚刚'
	} else if (minC >= 1 && minC <= 59) {
		result = parseInt(minC) + '分钟前'
	} else if (hourC >= 1 && hourC <= 23) {
		result = parseInt(hourC) + '小时前'
	} else if (dayC >= 1 && dayC < 3) {
		result = parseInt(dayC) + '天前'
	} else if (dayC >= 3 && dayC <= 7) {
		result = '3天前'
	} else {
		result = formatDate(timestamp, format)
	}

	return result
}

/**
 * param 将要转为URL参数字符串的对象
 * key URL参数字符串的前缀
 * encode true/false 是否进行URL编码,默认为true
 *
 * return URL参数字符串
 */
const urlEncode = (param, key, encode) => {
	if (param == null) return ''
	const t = typeof(param)
	let paramStr = ''
	if (t === 'string' || t === 'number' || t === 'boolean') {
		paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param)
	} else {
		for (let i in param) {
			let k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '[' + i + ']')
			paramStr += urlEncode(param[i], k, encode)
		}
	}

	return paramStr
}

/**
 * return
 */
const urlDecode = (query) => {
	if (!query) return null
	let hash, object = {}
	const hashes = query.slice(query.indexOf('?') + 1).split('&')
	for (let i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=')
		object[hash[0]] = hash[1]
	}

	return object;
}

/**
 * 对象合并
 */
const deepAssign = (origin, source) => {
	for (let key in source) {
		if (source.hasOwnProperty(key)) {
			if (source[key] instanceof Object) {
				deepAssign(origin[key], source[key])
			} else {
				origin[key] = source[key]
			}
		}
	}
}

/**
 * 状态数据
 */
const display = {
	toast: false, // 无用
	modal: false,
	loading: false,
}

// 显示消息提示
const showToast = function(text, icon) {
	wx.showToast({
		title: text || '加载中',
		icon: icon || 'none',
		mask: true,
		duration: 2000
	})
}

// 隐藏消息提示
const hideToast = function() {
	wx.hideToast()
}

// 显示 loading
const showLoading = function(text) {
	if (!display.loading) {
		display.loading = true
		wx.showLoading({
			title: text || '加载中',
			mask: true
		})
	}
}

// 隐藏 loading
const hideLoading = function() {
	if (display.loading) {
		display.loading = false
		wx.hideLoading()
	}
}

// 显示失败提示
const showModal = (title, content) => {
	if (display.toast) hideToast()
	if (display.loading) hideLoading()

	if (!display.modal) {
		title = title || '信息提示'
		content = content || '未知错误' // content 为 null 时会报错
		display.modal = true
		wx.showModal({
			title,
			content: typeof content === 'object' ? JSON.stringify(content) : content,
			showCancel: false,
			confirmColor: '#3B99FC',
			complete: function(e) {
				display.modal = false
			}
		})
	}
}

export function buildPageUrl(page, options) {
	let pageUrl = page;
	if (options) {
		let params = urlEncode(options)
		pageUrl += '?' + params.substring(1, params.length);
	}

	return pageUrl;
}

export function encodeRedirectUrl(page, options) {
	return encodeURIComponent(buildPageUrl(page, options));
}

export function decodeRedirectUrl(url) {
	return decodeURIComponent(url);
}

/**
 * 处理富文本里的图片宽度自适应
 * 1.去掉img标签里的style、width、height属性
 * 2.img标签添加style属性：max-width:100%;height:auto
 * 3.修改所有style里的width属性为max-width:100%
 * 4.去掉<br/>标签
 * 
 * @param html
 * @returns {void|string|*}
 */
export function formatRichText(html) {
	let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
		match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
		match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
		match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
		return match;
	});
	newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
		match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
		return match;
	});
	newContent = newContent.replace(/<br[^>]*\/>/gi, '');
	newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"');
	return newContent;
}


/** 
 * H5图片压缩 
 */
export function compressImage(file, maxWidth, maxHeight) {
	const setting = {
		maxWidth: maxWidth || 800,
		maxHeight: maxHeight || 800,
		quality: 0.9
	}
	console.log('compressImage', file, setting)

	return new Promise((resolve, reject) => {
		// 判断是否需要压缩, 没有超过限制
		if (file.size <= 1024 * 1024) {
			console.log('no compress')
			return resolve([null, file.path])
		} else {
			console.log('yes compress')
			uni.getImageInfo({
				src: file.path
			}).then(([err, res]) => {
				let img = new Image()
				img.src = res.path
				// 图片高宽
				let originWidth = res.width
				let originHeight = res.height
				let targetWidth = originWidth
				let targetHeight = originHeight
				let maxWidth = setting.maxWidth
				let maxHeight = setting.maxHeight
				if (originWidth > maxWidth || originHeight > maxHeight) {
					if (originWidth / originHeight > maxWidth / maxHeight) {
						targetWidth = maxWidth
						targetHeight = Math.round(maxWidth * (originHeight / originWidth))
					} else {
						targetHeight = maxHeight
						targetWidth = Math.round(maxHeight * (originWidth / originHeight))
					}
				}

				// 图片尺寸调整
				let canvas = document.createElement('canvas')
				canvas.width = targetWidth
				canvas.height = targetHeight
				let ctx = canvas.getContext('2d')
				ctx.drawImage(img, 0, 0, targetWidth, targetHeight)

				// 图片压缩导出
				canvas.toBlob(function(fileSrc) {
					let imgSrc = window.URL.createObjectURL(fileSrc)
					console.log('after compress', imgSrc)

					return resolve([null, imgSrc])
				}, 'image/jpeg', setting.quality)
			})
		}
	})
}

export function isWechat() {
	const ua = window.navigator.userAgent.toLowerCase()
	if (ua.match(/micromessenger/i) == 'micromessenger') {
		return true
	}

	return false
}


export default {
	extend,
	toDecimal,
	getTimestamp,
	formatDate,
	timeAgo,
	urlEncode,
	urlDecode,
	deepAssign,
	showToast,
	hideToast,
	showLoading,
	hideLoading,
	showModal,
	formatRichText,
	encodeRedirectUrl,
	decodeRedirectUrl
}
